package org.bookie.web.framework;

import org.apache.tapestry.engine.ExternalService;
import org.apache.tapestry.engine.ServiceEncoder;
import org.apache.tapestry.engine.ServiceEncoding;
import org.apache.tapestry.services.ServiceConstants;

/**
 * {@link ServiceEncoder} for encoding selected {@link ExternalService} links to
 * more RESTfull style.
 * 
 * For example link to event would be encoded as: "/event-24.html" link to the
 * user will be encoded as "/user_13.html"
 * 
 * @author zubairov
 */
public class RestfullServiceEncoder implements ServiceEncoder {

	private static final String EVENT_PAGE_NAME = "EventDetails";
	private static final String EVENT_SERVLET_PATH = "/event";
	private static final String USER_SERVLET_PATH = "/user";	
	private static final String USER_PAGE_NAME = "UserDetails";
	
	/**
	 * {@inheritDoc}
	 */
	public void decode(ServiceEncoding encoding) {
		String servletPath = encoding.getServletPath();
		if (servletPath.startsWith(EVENT_SERVLET_PATH)) {
			String id = encoding.getPathInfo();
			if (id == null) {
				return;
			}
			encoding.setParameterValue(ServiceConstants.SERVICE, "external");
			encoding.setParameterValue(ServiceConstants.PAGE, EVENT_PAGE_NAME);
			encoding.setParameterValue(ServiceConstants.PARAMETER, "l" + id.substring(1));
		}
		if (servletPath.startsWith(USER_SERVLET_PATH)) {
			String id = encoding.getPathInfo();
			if (id == null) {
				return;
			}
			encoding.setParameterValue(ServiceConstants.SERVICE, "external");
			encoding.setParameterValue(ServiceConstants.PAGE, USER_PAGE_NAME);
			encoding.setParameterValue(ServiceConstants.PARAMETER, "l" + id.substring(1));
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void encode(ServiceEncoding encoding) {
		String service = encoding.getParameterValue(ServiceConstants.SERVICE);

		if (service == null || !service.equals("external"))
			return;

		String pageName = encoding.getParameterValue(ServiceConstants.PAGE);
		if (EVENT_PAGE_NAME.equals(pageName)) {
			updateEncoding(encoding, EVENT_SERVLET_PATH);
			return;
		}
		if (USER_PAGE_NAME.equals(pageName)) {
			updateEncoding(encoding, USER_SERVLET_PATH);
			return;
		}
	}

	private void updateEncoding(ServiceEncoding encoding, String servletPath) {
		String id = encoding.getParameterValue(ServiceConstants.PARAMETER);
		StringBuffer buffer = new StringBuffer(servletPath);
		buffer.append("/");
		buffer.append(id.substring(1));
		encoding.setParameterValue(ServiceConstants.SERVICE, null);
		encoding.setParameterValue(ServiceConstants.PAGE, null);
		encoding.setParameterValue(ServiceConstants.PARAMETER, null);
		encoding.setServletPath(buffer.toString());
	}

}
